home *** CD-ROM | disk | FTP | other *** search
/ Tech Arsenal 1 / Tech Arsenal (Arsenal Computer).ISO / tek-01 / ohlutil.zip / CAT.C < prev    next >
C/C++ Source or Header  |  1990-06-20  |  17KB  |  709 lines

  1. /* cat -- concatenate files and print on the standard output.
  2.    Copyright (C) 1988, 1990 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 1, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  17.  
  18. /* Differences from the Unix cat:
  19.    * Always unbuffered, -u is ignored.
  20.    * 100 times faster with -v -u.
  21.    * 20 times faster with -v.
  22.    * Warnings about nonexisting files are delayed until everything has
  23.      been written out.  This is nice if output is to a terminal.
  24.  
  25.    By tege@sics.se, Torbjorn Granlund, advised by rms, Richard Stallman. */
  26.  
  27. #include <stdio.h>
  28. #include <errno.h>
  29. #include <sys/types.h>
  30. #ifndef _POSIX_SOURCE
  31. #include <sys/ioctl.h>
  32. #endif
  33. #include "system.h"
  34. #include "getopt.h"
  35.  
  36. #ifdef STDC_HEADERS
  37. #include <stdlib.h>
  38. #else
  39. char *malloc ();
  40. int free ();
  41.  
  42. extern int errno;
  43. #endif
  44.  
  45. #define max(h,i) ((h) > (i) ? (h) : (i))
  46.  
  47. typedef unsigned char uchar;
  48.  
  49. char *copystring ();
  50. void cat ();
  51. void error ();
  52. void next_line_num ();
  53. void simple_cat ();
  54.  
  55. /* Name under which this program was invoked.  */
  56.  
  57. char *program_name;
  58.  
  59. /* Name of input file.  May be "-".  */
  60.  
  61. char *infile;
  62.  
  63. /* Descriptor on which input file is open.  */
  64.  
  65. int input_desc;
  66.  
  67. /* Descriptor on which output file is open.  Always is 1.  */
  68.  
  69. int output_desc;
  70.  
  71. /* Buffer for line numbers.  */
  72.  
  73. char line_buf[13] =
  74. {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '0', '\t', '\0'};
  75.  
  76. /* Position in `line_buf' where printing starts.  This will not change
  77.    unless the number of lines are more than 999999.  */
  78.  
  79. char *line_num_print = line_buf + 5;
  80.  
  81. /* Position of the first digit in `line_buf'.  */
  82.  
  83. char *line_num_start = line_buf + 10;
  84.  
  85. /* Position of the last digit in `line_buf'.  */
  86.  
  87. char *line_num_end = line_buf + 10;
  88.  
  89. /* Preserves the `cat' function's local `newlines' between invocations.  */
  90.  
  91. int newlines2 = 0;
  92.  
  93. void
  94. usage (reason)
  95.      char *reason;
  96. {
  97.   if (reason != NULL)
  98.     fprintf (stderr, "%s: %s\n", program_name, reason);
  99.  
  100.   fprintf (stderr, "\
  101. Usage: %s [-bcenstuvAET] [+number] [+number-nonblank] [+squeeze-blank]\n\
  102.        [+show-nonprinting] [+show-ends] [+show-tabs] [+show-all] [file...]\n",
  103.        program_name);
  104.  
  105.   exit (2);
  106. }
  107.  
  108.  
  109. void
  110. main (argc, argv)
  111.      int argc;
  112.      char *argv[];
  113. {
  114.   /* Optimal size of i/o operations of output.  */
  115.   int outsize;
  116.  
  117.   /* Optimal size of i/o operations of input.  */
  118.   int insize;
  119.  
  120.   /* Pointer to the input buffer.  */
  121.   uchar *inbuf;
  122.  
  123.   /* Pointer to the output buffer.  */
  124.   uchar *outbuf;
  125.  
  126.   int c;
  127.  
  128.   /* Index in argv to processed argument.  */
  129.   int argind;
  130.  
  131.   /* Array of boolean values telling whether an input file exists and is
  132.      readable.  */
  133.   short *argbad;
  134.  
  135.   /* Device number of the output (file or whatever).  */
  136.   int out_dev;
  137.  
  138.   /* I-node number of the output.  */
  139.   int out_ino;
  140.  
  141.   /* Nonzero if the output file should not be the same as any input file. */
  142.   int check_redirection = 1;
  143.  
  144.   struct stat stat_buf;
  145.  
  146.   /* Count of non-fatal error conditions.  */
  147.   int exit_stat = 0;
  148.  
  149.   /* Variables that are set according to the specified options.  */
  150.   int numbers = 0;
  151.   int numbers_at_empty_lines = 1;
  152.   int squeeze_empty_lines = 0;
  153.   int mark_line_ends = 0;
  154.   int quote = 0;
  155.   int output_tabs = 1;
  156.   int options = 0;
  157.   int longind;
  158.   static struct option long_options[] =
  159.   {
  160.     {"number-nonblank", 0, NULL, 'b'},
  161.     {"number", 0, NULL, 'n'},
  162.     {"squeeze-blank", 0, NULL, 's'},
  163.     {"show-nonprinting", 0, NULL, 'v'},
  164.     {"show-ends", 0, NULL, 'E'},
  165.     {"show-tabs", 0, NULL, 'T'},
  166.     {"show-all", 0, NULL, 'A'},
  167.     {NULL, 0, NULL, 0}
  168.   };
  169.  
  170.   program_name = argv[0];
  171.  
  172.   /* Parse command line options.  */
  173.  
  174.   while ((c = getopt_long (argc, argv, "bcenstuvAET", long_options, &longind))
  175.      != EOF)
  176.     {
  177.       options++;
  178.       if (c == 0)
  179.     c = long_options[longind].val;
  180.       switch (c)
  181.     {
  182.     case 'b':
  183.       numbers = 1;
  184.       numbers_at_empty_lines = 0;
  185.       break;
  186.  
  187.     case 'e':
  188.       mark_line_ends = 1;
  189.       quote = 1;
  190.       break;
  191.  
  192.     case 'n':
  193.       numbers = 1;
  194.       break;
  195.  
  196.     case 'c':        /* For POSIX. */
  197.     case 's':
  198.       squeeze_empty_lines = 1;
  199.       break;
  200.  
  201.     case 't':
  202.       output_tabs = 0;
  203.       quote = 1;
  204.       break;
  205.  
  206.     case 'u':
  207.       /* We provide the -u feature unconditionally.  */
  208.       options--;
  209.       break;
  210.  
  211.     case 'v':
  212.       quote = 1;
  213.       break;
  214.  
  215.     case 'A':
  216.       quote = 1;
  217.       mark_line_ends = 1;
  218.       output_tabs = 0;
  219.       break;
  220.  
  221.     case 'E':
  222.       mark_line_ends = 1;
  223.       break;
  224.  
  225.     case 'T':
  226.       output_tabs = 0;
  227.       break;
  228.  
  229.     default:
  230.       usage ((char *) 0);
  231.     }
  232.     }
  233.  
  234.   output_desc = fileno (stdout);
  235.  
  236.   /* Get device, i-node number, and optimal blocksize of output.  */
  237.  
  238.   if (fstat (output_desc, &stat_buf) < 0)
  239.     error (1, errno, "cannot fstat standard output");
  240.  
  241.   outsize = ST_BLKSIZE (stat_buf);
  242.   switch (stat_buf.st_mode & S_IFMT)
  243.     {
  244.       /* Input file can be output file for non-regular files.
  245.      fstat on pipes returns S_IFSOCK on some systems, S_IFIFO
  246.      on others, so the checking should not be done for those types,
  247.      and to allow things like cat < /dev/tty > /dev/tty, checking
  248.      is not done for device files either. */
  249.     case S_IFREG:
  250.       out_dev = stat_buf.st_dev;
  251.       out_ino = stat_buf.st_ino;
  252.       break;
  253.     default:
  254.       check_redirection = 0;
  255.       break;
  256.     }
  257.  
  258.   /* Check if any of the input files are the same as the output file.  */
  259.  
  260.   argbad = (short *) alloca ((argc + 1) * sizeof (short));
  261.  
  262.   /* Main loop.  */
  263.  
  264.   infile = "-";
  265.   argind = optind;
  266.  
  267.   do
  268.     {
  269.       argbad[argind] = 0;
  270.  
  271.       if (argind < argc)
  272.     infile = argv[argind];
  273.  
  274.       if (infile[0] == '-' && infile[1] == 0)
  275.     input_desc = fileno (stdin);
  276.       else
  277.     {
  278.       /* Open a file for input.  If the file cannot be opened, remember
  279.          the error number in argbad.  */
  280.  
  281.       input_desc = open (infile, O_RDONLY);
  282.       if (input_desc < 0)
  283.         {
  284.           argbad[argind] = errno;
  285.           exit_stat++;
  286.           continue;
  287.         }
  288.     }
  289.  
  290.       if (fstat (input_desc, &stat_buf) < 0)
  291.     error (1, errno, "%s", infile);
  292.       insize = ST_BLKSIZE (stat_buf);
  293.  
  294.       /* Compare the device and i-node numbers of this input file with
  295.      the corresponding values of the (output file associated with)
  296.      stdout, and skip this input file if they coincide.  Input
  297.      files cannot be redirected to themselves.  A warning will be
  298.      printed after all files have been processed.  This condition
  299.      is remembered in argbad.  */
  300.  
  301.       if (check_redirection
  302.       && stat_buf.st_dev == out_dev && stat_buf.st_ino == out_ino)
  303.     {
  304.       argbad[argind] = -1;
  305.       exit_stat++;
  306.       continue;
  307.     }
  308.  
  309.       /* Select which version of `cat' to use. If any options (more than -u)
  310.      were specified, use `cat', otherwise use `simple_cat'.  */
  311.  
  312.       if (options == 0)
  313.     {
  314.       insize = max (insize, outsize);
  315.       inbuf = (uchar *) malloc (insize);
  316.       if (inbuf == NULL)
  317.         error (1, 0, "virtual memory exhausted");
  318.  
  319.       simple_cat (inbuf, insize);
  320.     }
  321.       else
  322.     {
  323.       inbuf = (uchar *) malloc (insize + 1);
  324.       if (inbuf == NULL)
  325.         error (1, 0, "virtual memory exhausted");
  326.  
  327.       /* Why are (OUTSIZE  - 1 + INSIZE * 4 + 13) bytes allocated for
  328.          the output buffer?
  329.  
  330.          A test whether output needs to be written is done when the input
  331.          buffer empties or when a newline appears in the input.  After
  332.          output is written, at most (OUTSIZE - 1) bytes will remain in the
  333.          buffer.  Now INSIZE bytes of input is read.  Each input character
  334.          may grow by a factor of 4 (by the prepension of M-^).  If all
  335.          characters do, and no newlines appear in this block of input, we
  336.          will have at most (OUTSIZE - 1 + INSIZE) bytes in the buffer.  If
  337.          the last character in the preceeding block of input was a
  338.          newline, a line number may be written (according to the given
  339.          options) as the first thing in the output buffer. (Done after the
  340.          new input is read, but before processing of the input begins.)  A
  341.          line number requires seldom more than 13 positions.  */
  342.  
  343.       outbuf = (uchar *) malloc (outsize - 1 + insize * 4 + 13);
  344.       if (outbuf == NULL)
  345.         error (1, 0, "virtual memory exhausted");
  346.  
  347.       cat (inbuf, insize, outbuf, outsize, quote,
  348.            output_tabs, numbers, numbers_at_empty_lines, mark_line_ends,
  349.            squeeze_empty_lines);
  350.  
  351.       free (outbuf);
  352.     }
  353.  
  354.       free (inbuf);
  355.       if (input_desc)
  356.     close (input_desc);
  357.     }
  358.   while (++argind < argc);
  359.  
  360.   /* Print delayed warnings.  */
  361.  
  362.   infile = "-";
  363.   argind = optind;
  364.  
  365.   do
  366.     {
  367.       if (argind < argc)
  368.     infile = argv[argind];
  369.  
  370.       if (infile[0] == '-' && infile[1] == 0)
  371.     infile = "standard input";
  372.  
  373.       if (argbad[argind])
  374.     {
  375.       if (argbad[argind] < 0)
  376.         error (0, 0, "%s: input file is output file", infile);
  377.       else
  378.         error (0, argbad[argind], "%s", infile);
  379.     }
  380.     }
  381.   while (++argind < argc);
  382.  
  383.   exit (exit_stat != 0);
  384. }
  385.  
  386. /* Plain cat.  Copies the file behind `input_desc' to the file behind
  387.    `output_desc'.  */
  388.  
  389. void
  390. simple_cat (buf, bufsize)
  391.      /* Pointer to the buffer, used by reads and writes.  */
  392.      uchar *buf;
  393.  
  394.      /* Number of characters preferably read or written by each read and write
  395.         call.  */
  396.      int bufsize;
  397. {
  398.   /* Actual number of characters read, and therefore written.  */
  399.   int n_read;
  400.  
  401.   /* Loop until the end of the file.  */
  402.  
  403.   for (;;)
  404.     {
  405.       /* Read a block of input.  */
  406.  
  407.       n_read = read (input_desc, buf, bufsize);
  408.       if (n_read < 0)
  409.     error (1, errno, "%s", infile);
  410.  
  411.       /* End of this file?  */
  412.  
  413.       if (n_read == 0)
  414.     break;
  415.  
  416.       /* Write this block out.  */
  417.  
  418.       if (write (output_desc, buf, n_read) != n_read)
  419.     error (1, errno, "write error");
  420.     }
  421. }
  422.  
  423. /* Cat the file behind INPUT_DESC to the file behind OUTPUT_DESC.
  424.    Called if any option more than -u was specified.
  425.  
  426.    A newline character is always put at the end of the buffer, to make
  427.    an explicit test for buffer end unnecessary.  */
  428.  
  429. void
  430. cat (inbuf, insize, outbuf, outsize, quote,
  431.      output_tabs, numbers, numbers_at_empty_lines,
  432.      mark_line_ends, squeeze_empty_lines)
  433.  
  434.      /* Pointer to the beginning of the input buffer.  */
  435.      uchar *inbuf;
  436.  
  437.      /* Number of characters read in each read call.  */
  438.      int insize;
  439.  
  440.      /* Pointer to the beginning of the output buffer.  */
  441.      uchar *outbuf;
  442.  
  443.      /* Number of characters written by each write call.  */
  444.      int outsize;
  445.  
  446.      /* Variables that have values according to the specified options.  */
  447.      int quote;
  448.      int output_tabs;
  449.      int numbers;
  450.      int numbers_at_empty_lines;
  451.      int mark_line_ends;
  452.      int squeeze_empty_lines;
  453. {
  454.   /* Last character read from the input buffer.  */
  455.   uchar ch;
  456.  
  457.   /* Pointer to the next character in the input buffer.  */
  458.   uchar *bpin;
  459.  
  460.   /* Pointer to the first non-valid byte in the input buffer, i.e. the
  461.      current end of the buffer.  */
  462.   uchar *eob;
  463.  
  464.   /* Pointer to the position where the next character shall be written.  */
  465.   uchar *bpout;
  466.  
  467.   /* Number of characters read by the last read call.  */
  468.   int n_read;
  469.  
  470.   /* The variable NEWLINES determines how many consequtive newlines there have
  471.      been in the input.  0 newlines makes NEWLINES -1, 1 newline makes
  472.      NEWLINES 1, etc.  Initially 0 to indicate that we are at the beginning of
  473.      a new line.  The "state" of the procedure is determined by NEWLINES.  */
  474.   int newlines = newlines2;
  475.  
  476. #ifdef FIONREAD
  477.   /* If nonzero, use the FIONREAD ioctl, as an optimization.
  478.      (On Ultrix, it is not supported on NFS filesystems.)  */
  479.   int use_fionread = 1;
  480. #endif
  481.  
  482.   /* The inbuf pointers are initialized so that BPIN > EOB, and thereby input
  483.      is read immediately.  */
  484.  
  485.   eob = inbuf;
  486.   bpin = eob + 1;
  487.  
  488.   bpout = outbuf;
  489.  
  490.   for (;;)
  491.     {
  492.       do
  493.     {
  494.       /* Write if there are at least OUTSIZE bytes in OUTBUF.  */
  495.  
  496.       if (bpout - outbuf >= outsize)
  497.         {
  498.           uchar *wp = outbuf;
  499.           do
  500.         {
  501.           if (write (output_desc, wp, outsize) != outsize)
  502.             error (1, errno, "write error");
  503.           wp += outsize;
  504.         }
  505.           while (bpout - wp >= outsize);
  506.  
  507.           /* Move the remaining bytes to the beginning of the
  508.          buffer.  */
  509.  
  510.           bcopy (wp, outbuf, bpout - wp);
  511.           bpout = outbuf + (bpout - wp);
  512.         }
  513.  
  514.       /* Is INBUF empty?  */
  515.  
  516.       if (bpin > eob)
  517.         {
  518. #ifdef FIONREAD
  519.           int n_to_read = 0;
  520.  
  521.           /* Is there any input to read immediately?
  522.          If not, we are about to wait,
  523.          so write all buffered output before waiting.  */
  524.  
  525.           if (use_fionread
  526.           && ioctl (input_desc, FIONREAD, &n_to_read) < 0)
  527.         {
  528.           if (errno == EOPNOTSUPP)
  529.             use_fionread = 0;
  530.           else
  531.             error (1, errno, "cannot do ioctl on `%s'", infile);
  532.         }
  533.           if (n_to_read == 0)
  534. #endif
  535.         {
  536.           int n_write = bpout - outbuf;
  537.  
  538.           if (write (output_desc, outbuf, n_write) != n_write)
  539.             error (1, errno, "write error");
  540.           bpout = outbuf;
  541.         }
  542.  
  543.           /* Read more input into INBUF.  */
  544.  
  545.           n_read = read (input_desc, inbuf, insize);
  546.           if (n_read < 0)
  547.         error (1, errno, "%s", infile);
  548.           if (n_read == 0)
  549.         {
  550.           newlines2 = newlines;
  551.           return;
  552.         }
  553.  
  554.           /* Update the pointers and insert a sentinel at the buffer
  555.          end.  */
  556.  
  557.           bpin = inbuf;
  558.           eob = bpin + n_read;
  559.           *eob = '\n';
  560.         }
  561.       else
  562.         {
  563.           /* It was a real (not a sentinel) newline.  */
  564.  
  565.           /* Was the last line empty?
  566.          (i.e. have two or more consecutive newlines been read?)  */
  567.  
  568.           if (++newlines > 0)
  569.         {
  570.           /* Are multiple adjacent empty lines to be substituted by
  571.              single ditto (-s), and this was the second empty line?  */
  572.  
  573.           if (squeeze_empty_lines && newlines >= 2)
  574.             {
  575.               ch = *bpin++;
  576.               continue;
  577.             }
  578.  
  579.           /* Are line numbers to be written at empty lines (-n)?  */
  580.  
  581.           if (numbers && numbers_at_empty_lines)
  582.             {
  583.               next_line_num ();
  584.               bpout = (uchar *) copystring (bpout, line_num_print);
  585.             }
  586.         }
  587.  
  588.           /* Output a currency symbol if requested (-e).  */
  589.  
  590.           if (mark_line_ends)
  591.         *bpout++ = '$';
  592.  
  593.           /* Output the newline.  */
  594.  
  595.           *bpout++ = '\n';
  596.         }
  597.       ch = *bpin++;
  598.     }
  599.       while (ch == '\n');
  600.  
  601.       /* Are we at the beginning of a line, and line numbers are requested?  */
  602.  
  603.       if (newlines >= 0 && numbers)
  604.     {
  605.       next_line_num ();
  606.       bpout = (uchar *) copystring (bpout, line_num_print);
  607.     }
  608.  
  609.       /* Here CH cannot contain a newline character.  */
  610.  
  611.       /* The loops below continue until a newline character is found,
  612.      which means that the buffer is empty or that a proper newline
  613.      has been found.  */
  614.  
  615.       /* If quoting, i.e. at least one of -v, -e, or -t specified,
  616.      scan for chars that need conversion.  */
  617.       if (quote)
  618.     for (;;)
  619.       {
  620.         if (ch >= 32)
  621.           {
  622.         if (ch < 127)
  623.           *bpout++ = ch;
  624.         else if (ch == 127)
  625.           *bpout++ = '^',
  626.             *bpout++ = '?';
  627.         else
  628.           {
  629.             *bpout++ = 'M',
  630.               *bpout++ = '-';
  631.             if (ch >= 128 + 32)
  632.               if (ch < 128 + 127)
  633.             *bpout++ = ch - 128;
  634.               else
  635.             *bpout++ = '^',
  636.               *bpout++ = '?';
  637.             else
  638.               *bpout++ = '^',
  639.             *bpout++ = ch - 128 + 64;
  640.           }
  641.           }
  642.         else if (ch == '\t' && output_tabs)
  643.           *bpout++ = '\t';
  644.         else if (ch == '\n')
  645.           {
  646.         newlines = -1;
  647.         break;
  648.           }
  649.         else
  650.           *bpout++ = '^',
  651.         *bpout++ = ch + 64;
  652.  
  653.         ch = *bpin++;
  654.       }
  655.       else
  656.     /* Not quoting, neither of -v, -e, or -t specified.  */
  657.     for (;;)
  658.       {
  659.         if (ch == '\t' && !output_tabs)
  660.           *bpout++ = '^',
  661.         *bpout++ = ch + 64;
  662.         else if (ch != '\n')
  663.           *bpout++ = ch;
  664.         else
  665.           {
  666.         newlines = -1;
  667.         break;
  668.           }
  669.  
  670.         ch = *bpin++;
  671.       }
  672.     }
  673. }
  674.  
  675. /* Compute the next line number.  */
  676.  
  677. void
  678. next_line_num ()
  679. {
  680.   char *endp = line_num_end;
  681.   do
  682.     {
  683.       if ((*endp)++ < '9')
  684.     return;
  685.       *endp-- = '0';
  686.     }
  687.   while (endp >= line_num_start);
  688.   *--line_num_start = '1';
  689.   if (line_num_start < line_num_print)
  690.     line_num_print--;
  691. }
  692.  
  693. /* A less stupid strcpy.  Returns a pointer to the end of the destination
  694.    string, instead of to the beginning.  Doesn't null-terminate the
  695.    destination.  */
  696.  
  697. char *
  698. copystring (dst, src)
  699.      char *dst;
  700.      char *src;
  701. {
  702.   char c;
  703.  
  704.   while (c = *src++)
  705.     *dst++ = c;
  706.  
  707.   return dst;
  708. }
  709.